<!--
 * @Description: 
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2023-07-10 16:45:35
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <h1>websockets简单示例</h1><br>
    <div id="message"></div>
    <div>
        <input type="text" id="sendText">
        <button id="connect" onclick="connect()">建立连接</button>
        <button id="sendData" onclick="sendData()">发送数据</button>
        <button id="closeConnect" onclick="closeConnect()">关闭连接</button>
    </div>
</body>
<script type="text/javascript">
    let websockets;
    //创建一个数组对象用于存放当前的连接的状态，以便在页面上实时展示出来当前的状态
    let statusArr = [
        { state: 0, value: '正在连接' },
        { state: 1, value: '已建立连接' },
        { state: 2, value: '正在关闭连接' },
        { state: 3, value: '已关闭连接' },
    ]
    /**
    *   建立连接
    *
    */
    function connect() {
        // 1. 创建websockets对象，参数为服务器websockets地址
        websockets = new WebSocket('wss://192.168.5.240:2333/')
        // 2.监听websocket的状态变化，接收的信息，关闭时的状态

        //监听连接状态的变化
        websockets.onopen = (event) => socketChange();

        //监听接收消息的情况
        websockets.onmessage = (res) => {
            document.querySelector("#message").innerHTML += `<p>接收数据: ${res.data}</p>`
        }

        //监听关闭时的状态变化
        websockets.onclose = (event) => socketChange();
    }
    /**
    *   socket状态变化
    *
    */
    function socketChange() {
        let state = websockets.readyState;
        let val = statusArr.map((item) => {
            if (item.state == state) {
                return item.value
            }
        });

        //实时显示状态的变化
        document.querySelector("#message").innerHTML += `<p>当前的socket连接状态是: ${val}</p>`
    }
    /**
    *   发送数据
    *
    */
    function sendData() {
        //1. 首先获取输入的信息，判断信息是否可以发送
        let val = document.querySelector("#sendText").value;

        if (val == "" || val == undefined) {
            document.querySelector("#message").innerHTML += "<p>发送数据为空，请填写完成后再发送！</p>";
            return;
        }

        websockets.send(val);
        document.querySelector("#message").innerHTML += `<p>发送数据:${val}</p>`;
    }
    /**
    *   关闭连接
    *
    */
    function closeConnect() {
        websockets.close();
    }
</script>

</html>
